package com.cuzofu.fs.controller;

import cn.hutool.core.util.RandomUtil;
import com.cuzofu.fs.common.Constant;
import com.cuzofu.fs.common.R;
import com.cuzofu.fs.common.exception.RRException;
import com.cuzofu.fs.po.PdfComparePO;
import com.cuzofu.fs.service.MinioTemplate;
import com.cuzofu.fs.utils.HttpHelp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

/**
 * 文件服务
 *
 * @author cuzofu
 */
@RestController
@RequestMapping("file")
public class FileController {

    @Autowired
    private MinioTemplate minioTemplate;

    @GetMapping("/test")
    public R test() {
        return new R();
    }

    @PostMapping("/upload")
    public R upload(@RequestParam MultipartFile file) {
        try {
            String fileName = RandomUtil.randomUUID();
            minioTemplate.putObject("cuzofu", fileName, file.getInputStream(), file.getSize(), file.getContentType());
            return R.ok()
                    .put("id", fileName)
                    .put("url", String.format("/%s/%s", Constant.BUCKET_NAME, fileName))
                    .put("originalFilename", file.getOriginalFilename());
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    @PostMapping("/compareUpload")
    public R upload(@RequestParam MultipartFile mFile, @RequestParam MultipartFile oFile) {
        try {
            String mFileName = RandomUtil.randomUUID();
            minioTemplate.putObject(Constant.BUCKET_NAME, mFileName, mFile.getInputStream(), mFile.getSize(), mFile.getContentType());
            String oFileName = RandomUtil.randomUUID();
            minioTemplate.putObject(Constant.BUCKET_NAME, oFileName, oFile.getInputStream(), oFile.getSize(), oFile.getContentType());
            Map<String, String> result = new HashMap<>();
            result.put("oUrl", String.format("/%s/%s", Constant.BUCKET_NAME, oFileName));
            result.put("mUrl", String.format("/%s/%s", Constant.BUCKET_NAME, mFileName));
            return new R(result);
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    @GetMapping("/getBase64String")
    public R getBase64String(PdfComparePO po) {
        String m = getFileBase64(po.getmUrl());
        String o = getFileBase64(po.getoUrl());
        return R.ok().put("m", m).put("o", o);
    }

    @PostMapping("/compareTest")
    public R compareTest(@RequestBody PdfComparePO po) {

        try {
            String m = getFileBase64(po.getmUrl());
            String o = getFileBase64(po.getmUrl());
            Map<String, Object> map = new HashMap<>();
            List<String> columns = new ArrayList<>();
            columns.add("pdf_m");
            columns.add("pdf_o");
            map.put("columns", columns);
            List<Integer> index = new ArrayList<>();
            index.add(0);
            map.put("index", index);
            List<List<String>> data = new ArrayList<>();
            List<String> item = new ArrayList<>();
            item.add(m);
            item.add(o);
            data.add(item);
            map.put("data", data);
            String response = HttpHelp.sendPost("http://58.49.44.122:11080/invocations", map);
        } catch (Exception e) {
            throw new RRException(e.getMessage());
        }

        return R.ok();
    }

    /**
     * pdf文件比对
     */
    @PostMapping("/compare")
    public R pdfCompare(@RequestBody PdfComparePO po) {
        try {
            String m = getFileBase64(po.getmUrl());
            String o = getFileBase64(po.getmUrl());
            Map<String, Object> map = new HashMap<>();
            String[] columns = {"pdf_m", "pdf_o"};
            String[] index = {"0"};
            String[] data = {m, o};
            map.put("columns", columns);
            map.put("index", index);
            map.put("data", data);
            String response = HttpHelp.sendPost("http://58.49.44.122:11080/invocations", map);
            return R.ok().put("result", response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.ok();
    }

    private String getFileBase64(String url) {

        InputStream is = returnBitMap(url);
        return getBase64FromInputStream(is);

    }

    public static String getBase64FromInputStream(InputStream in) {
        // 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        byte[] data = null;
        // 读取图片字节数组
        try {
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            byte[] buff = new byte[100];
            int rc;
            while ((rc = in.read(buff, 0, 100)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            data = swapStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Base64.getEncoder().encodeToString(data);
    }

    public InputStream returnBitMap(String path) {
        InputStream is = null;
        try {
            URL url = new URL(path);
            //利用HttpURLConnection对象,我们可以从网络中获取网页数据
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.connect();
            is = conn.getInputStream();    //得到网络返回的输入流

        } catch (Exception e) {
            e.printStackTrace();
        }
        return is;
    }
}
